<?php

/*
 * This file is used to show the documents that have been connected with the user, along with its 'track document'.
 * 
 * Created by: Peter Agno Jr.
 * Date created: October 12, 2011
 */

    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // Connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    $userId = $_SESSION['loggedUserId'];
    $circleVersion = "5";
    $lineWidth = "27";
    $lineHeight = "21";
    $circleWidth = "21";
    $circleHeight = "21";
    
    // This is used for the yellow arrow when there are subroutes
    $ylwArrwPadTop = 10;
//    $ylwArrwPadLeft = 253;
    $ylwArrwPadLeft = 0;
    $ylwArrwWidth = 23;
    $ylwArrwHeight = 100;
    
    // ****************************************************************************
    // Start - Write functions here
    
    // Function - isRejected
    include("includes/functions/checkDocRejected.php");
    
    // Start - Check the permission of the user if it has VIEWALLDOCS
    function allDocsPerm($theUserId) {
        $query = 
        "
            SELECT *
            FROM Account_Dept_Pos as ADP, Dept_Pos_SecurityGroup as DPSG, SecurityGroup_Permission as SGP            
            WHERE ADP.userId = '$theUserId' AND ADP.deptPosId = DPSG.deptPosId AND DPSG.securityGroupId = SGP.securityGroupId AND SGP.permissionId = 'VIEWALLDOCS'
        ";

        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());

        if ( mysql_fetch_array($result) != 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // End - Check the permission of the user if it has VIEWALLDOCS
    
    // Start - Append the color of the circle
    function addCircle($documentId, $color, $stepId, $index, $totalStepCount, $tempStepNum, $thePath, $altColor, $circleVersion, $circleWidth, $circleHeight) {
        $tmpAddCrcle = "";
        $tmpAddCrcle = $tmpAddCrcle . "<img class='trackCircles' id='". $documentId ."__". $color ."__". $stepId ."__". $index ."__". $totalStepCount ."__". $tempStepNum ."' src='images/trackDoc/version".$circleVersion."/". $thePath ."' alt='". $altColor ."' width='".$circleWidth."' height='".$circleHeight."' />";
        return $tmpAddCrcle;
    } // End - Append the color of the circle
    
    function isCancelled ($documentId) {
        // Check in Logs
        $query =
            "
                SELECT *
                FROM Log
                WHERE documentId = '$documentId' AND activity = 'Cancelled'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_num_rows($result) > 0 ) {
            mysql_free_result($result);
            return true;
        }
        else {
            mysql_free_result($result);
            return false;
        }
    }
    
    // Start - Return the stepId on log depending on the activity
    function getStepId($documentId, $theActivity) {
        // Check in Logs
        $query =
            "
                SELECT *
                FROM Log
                WHERE documentId = '$documentId' AND activity = '$theActivity'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        return $row['stepId'];
    } // Start - Return the stepId on log depending on the activity
    
    // Start - Get the position initial depending on the stepId that will be passed
    function getPosInitial($stepId) {
        $query =
            "
                SELECT *
                FROM RouteStep_Dept_Pos as RSDP, Department_Position as DP
                WHERE RSDP.deptPosId = DP.deptPosId AND RSDP.stepId = '$stepId'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        return $row['positionId'];
    } // End - Get the position initial depending on the stepId that will be passed
    
    // Start - Prepare the append the category row
    function appendCategories($ctgryStorage) {
        $tmpCtgryVar = "";
        $archvCtgryArry = array();
        $archvCtgryArryCount = array();
        $tmpCtgryCount = 0;
        $tmpCtgryTr = "";
        
        // Start - Iterate stepId
        foreach ( $ctgryStorage as $aCtgry ) {
            if ( strtoupper($aCtgry) == strtoupper($tmpCtgryVar) ) {
                $tmpCtgryCount++;
            }
            else {
                // Do the following if it is not yet the first time
                if ( $tmpCtgryVar != "" ) {
                    $archvCtgryArry[] = $tmpCtgryVar;
                    $archvCtgryArryCount[] = $tmpCtgryCount;
                }
                
                $tmpCtgryVar = $aCtgry;
                $tmpCtgryCount = 1;
            }
        }// End - Iterate stepId 
        
        // Do the following for the last category
        if ( $tmpCtgryVar != "" ) {
            $archvCtgryArry[] = $tmpCtgryVar;
            $archvCtgryArryCount[] = $tmpCtgryCount;
        }
        
        // You now have the categories in arrays, place them now in tr properly
        
        $tmpCtgryTr = $tmpCtgryTr . "<tr>";
        for( $x = 0 ; $x < count($archvCtgryArry) ; $x++ ){
            $theCtgry = $archvCtgryArry[$x];
            $tempColspan = $archvCtgryArryCount[$x] + ($archvCtgryArryCount[$x] - 1) ;
            
            // Start - Compute for the padding left of the trackCategories class
            if ( $tempColspan <= 3 ) {
                $padLeft = 0; // for 2 track points
            }
            else if ( $tempColspan <= 5 ) {
                $padLeft = 3 * $tempColspan; // for 3 track points
            }
            else if ( $tempColspan < 13 ) {
                $padLeft = 5 * $tempColspan; // for 4 to 6 track points
            }
            else {
                $padLeft = 8 * $tempColspan; // for 7 or more track points
            }
            // End - Compute for the padding left of the trackCategories class
            
            // Start - Compute for the length of $borderIndicator
            $borderIndicator = "";
            $borderIndicator = $borderIndicator . "|";
            
            // Compute for the nomber of "-" in $borderIndicator
            $addBrdrLine = 0;
            if ( $tempColspan <= 1 ) {
                $multipleBrdrLine = 1; // for 1 track point
            }
            else if ( $tempColspan <= 3 ) {
                $multipleBrdrLine = 4; // for 2 track points
            }
            else if ( $tempColspan <= 5 ) {
                $multipleBrdrLine = 4; // for 3 track points
                $addBrdrLine = 4;
            }
            else if ( $tempColspan <= 9 ) {
                $multipleBrdrLine = 5; // for 4 or 5 track points
            }
            else {
                $multipleBrdrLine = 5; // for 6 or more track points
                $addBrdrLine = 8;
            }
            
            $borderLineComp = ($multipleBrdrLine * $tempColspan) + $addBrdrLine;
            
            for( $i = 0 ; $i < $borderLineComp ; $i++ ){
                $borderIndicator = $borderIndicator . "-";
            }
            $borderIndicator = $borderIndicator . "|";
            // End - Compute for the length of $borderIndicator
            
            $tmpCtgryTr = $tmpCtgryTr . "<td style='padding-bottom: 3px; border: 0px; text-align:center; font-size: 11;' colspan='".$tempColspan."'><div class='trackCategories' style='padding-left: ".$padLeft."px;'>".$theCtgry."</div> <br> ".$borderIndicator." </td>";
        
            // Pad another td if it not yet the last
            if ( $x != ( count($archvCtgryArry) -1 ) ) {
                $tmpCtgryTr = $tmpCtgryTr . "<td style='border: 0px;'></td>";
            }
        }
        $tmpCtgryTr = $tmpCtgryTr . "</tr>";
        
        return $tmpCtgryTr;
    } // End - Prepare the append the category row
    
    // Start - Display the track circles
    function displayTrackDocument($documentId, $addCircleNum, $stepIdStorage, $currentStep, $totalStepCount, $circleVersion, $circleWidth, $circleHeight, $lineWidth, $lineHeight, $printAllYlw, $ctgryStorage) {
        $trackDocInfo = "";
        
        // Make the track images small of the $totalStepCount is higher than 10
//        if ( $totalStepCount > 10 ) {
//            $lineWidth = "45";
//            $lineHeight = "21";
//            $circleWidth = "21";
//            $circleHeight = "21";
//        }

        // DISPLAY TRACK DOCUMENT
        $transition = false;    // this is a flag to show the transition line if the color is yellow
        $contLineYlw = false;   // Show yellow lines once the current step was shown
        $displayTrack = true;
        $i = 0;

        // create table, which will hold the track points
        $trackDocInfo = $trackDocInfo . "<table class='trackInnerTableBorder' style='border-top: 0px; '>";
        $tempCategories = appendCategories($ctgryStorage); // prepare the row for categories
        $trackDocInfo = $trackDocInfo . $tempCategories;
        $trackDocInfo = $trackDocInfo . "<tr>";
        
        do {
            $trackDocInfo = $trackDocInfo . "<td style='padding-left: 0px; padding-right: 0px; border: 0px; '>"; // td for track point
            
            // DISPLAY YELLOW, GREEN, OR GREY CIRCLES
            if( ($i < ( $currentStep - 1 ) || $currentStep == 0) && $printAllYlw == false ) {
                // Print green circles
                if ( $i == 0 ) {
                    // Print the first circle
                    $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/grn_nothov_frst.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                    $trackDocInfo = $trackDocInfo . $tempCircle;
                }
                else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/grn_nothov_last.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                else {
                    // Print the center circle
                    $tempCircle = addCircle($documentId, 'grn', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/grn_nothov_cntr.png', 'Green', $circleVersion, $circleWidth, $circleHeight);
                    $trackDocInfo = $trackDocInfo . $tempCircle;
                }
            }
            else {
                if ( $i == ( $currentStep - 1 ) ) {
                    // Print yellow circles
                    if ( $i == 0 ) {
                        // Print the first circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/ylw_blink2_frst.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/ylw_blink2_last.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else {
                        // Print the center circle
                        $tempCircle = addCircle($documentId, 'ylw', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/ylw_blink2_cntr.gif', 'Yellow', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }

                    $transition = true;
                }
                else {
                    // Print grey circles
                    if ( $i == 0 ) {
                        // Print the first circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'first/gry_nothov_frst.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else if ( $i == $totalStepCount-1 ) {
                        // Print the last circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'last/gry_nothov_last.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                    else {
                        // Print the center circle
                        $tempCircle = addCircle($documentId, 'gry', $stepIdStorage[$i], $i+1, $totalStepCount, $i+$addCircleNum, 'center/gry_nothov_cntr.png', 'Grey', $circleVersion, $circleWidth, $circleHeight);
                        $trackDocInfo = $trackDocInfo . $tempCircle;
                    }
                }
            }
            
            $posInitial = getPosInitial($stepIdStorage[$i]);
            $trackDocInfo = $trackDocInfo . "<div class='trackInitials'>".$posInitial."</div>"; // add position initial
            $trackDocInfo = $trackDocInfo . "</td>"; // close td of track point
            $i++;
            
            // DISPLAY LINE AND ARROW
            if( $i < $totalStepCount ) {
                $trackDocInfo = $trackDocInfo . "<td style='padding-left: 0px; padding-right: 0px; border: 0px;'>"; // td for line
                
                if ( $transition == true && $printAllYlw == false ) {
                    // print transition lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_trnsition.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                    $transition = false;
                    $contLineYlw = true;
                }
                else if ( $contLineYlw == true || $printAllYlw == true ) {
                    // print yellow lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_lght_ornge.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                }
                else {
                    // print orange lines
                    $trackDocInfo = $trackDocInfo . "<img src='images/trackDoc/version".$circleVersion."/line/line_drk_ornge.png' alt='Line' width='".$lineWidth."' height='".$lineHeight."'/>";
                }
                
                $trackDocInfo = $trackDocInfo . "</td>"; // close td of line
            }
            else {
                $displayTrack = false;
            }
        }while( $displayTrack == true );
    
        $trackDocInfo = $trackDocInfo . "</tr>"; // close tr
        $trackDocInfo = $trackDocInfo . "</table>"; // close table, which holds the track points
        
        return $trackDocInfo;
    } // End - Display the track circles
    
    // Start - Check if the document was rejected or cancelled in initial route
    function rejOrCnclInInitRoute($benchMarkStepId) {
        $inInitRoute = false;
        
        $query =
            "
                SELECT *
                FROM RouteStep
                WHERE stepId = '$benchMarkStepId'
            ";
    
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['subRouteId'] == null ) {
            $inInitRoute = true;
        }
        
        return $inInitRoute;
    } // End - Check if the document was rejected or cancelled in initial route
    
    // Start -  Check if the document is in initial route
    function inInitRoute($documentId) {
        $isInInitRoute = true;
        
        $query =
            "
                SELECT RS.subRouteId as subRouteId
                FROM MainDocument as MD, RouteStep as RS
                WHERE MD.mainDocumentId = '$documentId' AND MD.currentStepId = RS.stepId
            ";
    
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['subRouteId'] != null ) {
            $isInInitRoute = false;
        }
        
        return $isInInitRoute;
    } // End - Check if the document is in initial route
    
    // Start - Check if the document was rejected or cancelled in this subroute
    function hereActionSubRoute($documentId, $aSubRoute, $theAction) {
        $wasPerformedHere = false;

        $query = 
        "
            SELECT *
            FROM Log
            WHERE documentId = '$documentId' AND activity = '$theAction'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        $performedStepId = $row['stepId']; // You now have the step id on where the cancellation or rejection was performed

        $query = 
        "
            SELECT *
            FROM RouteStep
            WHERE stepId = '$performedStepId'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result); // You now have the subrouteId

        if ( $row['subRouteId'] == $aSubRoute ) {
            $wasPerformedHere = true;
        }

        return $wasPerformedHere;
    } // End - Check if the document was rejected or cancelled in this subroute
    
    // Start - Get the subroute name
    function getSubRouteName($aSubRoute) {
        $query = 
        "
            SELECT subRouteName
            FROM SubRoute
            WHERE subRouteId = '$aSubRoute'
        ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);

        return $row['subRouteName'];
    } // End - Get the subroute name
    
    
    // ****************************************************************************
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">        
        jQuery(document).ready(function(){ 
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#trackMainDoc-nav").addClass("highlightMenuBar");
            
            // if origStepCount is higher than 13, then changed the width of the origin table
            if ( jQuery("#origStepCount").val() >= 13 ) {
                var widthVal = '107.5%';
                jQuery("#originDocsTable").css({ 'width': widthVal });
            }
            
            // if passByStepCount is higher than 13, then changed the width of the origin table
            if ( jQuery("#passByStepCount").val() >= 13 ) {
                var widthVal = '107.5%';
                jQuery("#passByDocsTable").css({ 'width': widthVal });
            }
            
            // if allActvAdmStepCount is higher than 13, then changed the width of the origin table
            if ( jQuery("#allActvAdmStepCount").val() >= 13 ) {
                var widthVal = '107.5%';
                jQuery("#allActvAdmDocsTable").css({ 'width': widthVal });
            }
            
            // if allActvUsrStepCount is higher than 13, then changed the width of the origin table
            if ( jQuery("#allActvUsrStepCount").val() >= 13 ) {
                var widthVal = '107.5%';
                jQuery("#allActvUsrDocsTable").css({ 'width': widthVal });
            }
            
            // INCLUDE JQUERUES FOR TRACKING
            <?php 
//                include('includes/jqueries/jQTrackDoc.php'); 
            ?>
            // Start - Change the color of the track circles if it was hovered and unhovered
            function changeCircle(buttonId, theStepNum, theTotalStepNum, theColor, isHover) {
                var circleVersion = "5", fileFormat = "png";

                // Prepare the hover
                if ( isHover == true ) {
                    varHov = "hov";
                }
                else {
                    varHov = "nothov";
                    
                    // Prepare the file format and varHov for blinking of current track point
                    if ( theColor == "ylw" ) {
                        varHov = "blink2";
                        fileFormat = "gif";
                    }
                }

                // Prepare the variables
                if ( theStepNum  == 1 ) {
                    // Prepare the position
                    varPosition = "frst";
                    varFolder = "first";
                }
                else if ( theStepNum == theTotalStepNum ) {
                    // Prepare the position
                    varPosition = "last";
                    varFolder = "last";
                }
                else {
                    // Prepare the position
                    varPosition = "cntr";
                    varFolder = "center";
                }

                jQuery("#"+buttonId).attr("src", "images/trackDoc/version"+circleVersion+"/"+varFolder+"/"+theColor+"_"+varHov+"_"+varPosition+"."+fileFormat);
            } // End - Change the color of the track circles if it was hovered and unhovered

            // START - JQUERUES FOR TRACKING
            jQuery(".trackCircles").hover(
                function (mousePtr) {
                    // START - DO THE FOLLOWING DURING HOVER
                    buttonId = this.id;

                    // MODIFY THE POSITION SO THAT IT IS NOT THAT FAR FROM THE CIRCLE
                    topValue = mousePtr.pageY - 10;
                    leftValue = mousePtr.pageX - 130;

                    // MODIFY THE CSS POSITION BEFORE SHOWING
                    jQuery(".trackInvisibleInfo").css({ 'display': 'none', 'top': topValue, 'left': leftValue });

                    // CHECK FOR THE APPROPRIATE IMAGE
                    tempSubstr = buttonId.split('__');
                    theStepNum = tempSubstr[3];
                    theTotalStepNum = tempSubstr[4];

                    if ( tempSubstr[1] == "ylw" )
                        changeCircle(buttonId, theStepNum, theTotalStepNum, "ylw", true);
                    else {
                        if ( tempSubstr[1] == "grn" ) 
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "grn", true);
                        else
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "gry", true);
                    }


                    // START - AJAX THE NEEDED INFORMATIONS
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/trackDocInfo.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            documentId : tempSubstr[0],
                            stepId : tempSubstr[2]
                        },
                        success : function(data){
                            // SET THE INFORMATION IN THE DIV
                            setInfo = "<table style='border:0; margin-bottom:0px;'>";
                            setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>Step Number : </td><td style='border:0;'>"+ tempSubstr[3]+"</td></tr>";

                            if ( data.firstName != 'None' )
                                setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>User : </td><td style='border:0;'>"+ data.firstName + data.middleName + data.lastName+"</td></tr>";

                            setInfo += data.deptPos;

                            // DISPLAY ROLE
            //                            if ( data.firstName != 'None' )
            //                                setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>Role : </td><td style='border:0;'>"+ data.activity+"</td></tr>";

                            setInfo += "</table>";
                            // PUT THE INFORMATION IN THE DIV
                            jQuery(".trackInvisibleInfo").html(setInfo);
                            jQuery(".trackInvisibleInfo").show();
                        },
                        error : function() {
                            alert("Error in getting the document information.");
                        }
                    }); // END - AJAX THE NEEDED INFORMATIONS
                    // END - DO THE FOLLOWING DURING HOVER
                }, 
                function () {
                    // START - DO THE FOLLOWING DURING NOT HOVER
                    buttonId = this.id;

                    // CHECK FOR THE APPROPRIATE IMAGE
                    tempSubstr = buttonId.split('__');
                    theStepNum = tempSubstr[3];
                    theTotalStepNum = tempSubstr[4];

                    if ( tempSubstr[1] == "ylw" )
                       changeCircle(buttonId, theStepNum, theTotalStepNum, "ylw", false);
                    else {
                        if ( tempSubstr[1] == "grn" )
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "grn", false);
                        else
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "gry", false);
                    }


                    jQuery(".trackInvisibleInfo").hide();
                    // END - DO THE FOLLOWING DURING NOT HOVER
                }); // END - JQUERUES FOR TRACKING 
            // End - Include jquery for tracking
                    
            // Include document on ready jQuery for hiding scroll bars of track document if necessary
            <?php include('includes/jqueries/jQHideDivTrckScroll.php'); ?>
                
            // ############################## Start - Add includes here ##############################
            <?php             
                // INCLUDE - JQUERY FOR TRANSFERRING TO VIEW PAGE OF THE ACCOUNT
                include("includes/jqueries/jQViewPageTransfer.php"); 
            ?>
            // ############################## End - Add includes here ##############################
                      
        }); // END - (DOCUMENT READY FUNCTION)
    </script>
    <!-- HEAD END -->

<?php include("siteMiddle.php"); ?>

<div id="content">
    <h1>Track Main Document</h1>
    
    <?php
    // Check permission
    $thePermissions = array('VIEWMAIN');
    if ( checkPermission( $thePermissions, $userId ) == true ) {
    ?>
    
    <?php
    if ( allDocsPerm($userId) == false ) {
    ?>
        <!-- START - Display documents that were originated by the user -->
        <!-- Note : Display only the documents if it is not yet archived -->
            <?php
            // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
            $prevStepCount = 0;

            // GET THE DOCUMENTS
            $queryDocs =
                "
                    SELECT *
                    FROM
                        (
                            SELECT DS.documentName as documentName, MD.mainDocumentId as documentId, L.label as label
                            FROM MainDocument as MD, Account as A, DocumentSetup as DS, Document_Label as DL, Label as L
                            WHERE MD.originId = A.userId AND MD.documentSetupId = DS.documentSetupId AND A.userId = '$userId' AND MD.mainDocumentId = DL.documentId AND DL.mainLabel = '1' AND DL.labelId = L.labelId
                        ) as ConnectedDocs
                    WHERE documentId NOT IN
                        (SELECT documentId
                        FROM Log
                        WHERE activity = 'Archived')
                ";

            $docResults = mysql_query($queryDocs) or die ('Error in query: $queryDocs. ' . mysql_error());

            if ( mysql_num_rows($docResults) > 0 ) {
                // Start table
                echo "<span class='screenlet'>Routed Documents</span>";
                echo "<table border='1' id='originDocsTable' class='trckTableMainPage'>";
                
                // DISPLAY HEADERS
                echo "<tr>"; 
                echo "<td class='logHeader docIdTrck'>Document Id</td>";
                echo "<td class='logHeader docNameTrck'>Label</td>";
                echo "<td class='logHeader'>Track Document</td>";
                echo "</tr>";

                while( $docRow = mysql_fetch_array($docResults) ) {
                    echo "<tr>";
                    echo "<td><a href='javascript:;' class='hLinkViewPage' id='docId__".$docRow['documentId']."'>".$docRow['documentId']."</a></td>";
                    echo "<td>".$docRow['label']."</td>";
                    
                    // DISPLAY TRACK DOCUMENT
                    $documentId = $docRow['documentId'];
                    $pageCalled = "mainPgTrckDoc";  // Set the flag for track document that it will be to aligned to the left
                    include('trackDocument.php');

                    // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
                    if ( $prevStepCount < $totalStepCount )
                        $prevStepCount = $totalStepCount;

                    echo "</tr>";
                }

                mysql_free_result($docResults); // Free result
                echo "</table>"; // close table
            }
//            else {
//                // IF RETURNED QUERY IS EMPTY, THEN MESSAGE THE USER THAT THE RETURNED QUERY IS EMPTY
//                echo "<tr><td><span class='errorMessage'>No documents available.</span></td></tr>";
//            }
            ?>

        <!-- HIDDEN VARIABLES USED FOR ADJUSTMENT OF TABLE'S WIDTH -->
        <input id="origStepCount" name="origStepCount" type="hidden" value="<?php echo "$prevStepCount"; ?>" />
        <br/>
        <!-- END - Display documents that were originated by the user -->

        <!-- START - DISPLAY DOCUMENTS THAT WHERE PASSED BY THE USER -->
        <!-- Note : Do not show documents that the origin is this user -->
            <?php
            // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
            $prevStepCount = 0;

            // GET THE DOCUMENTS
            $queryDocs =
                "
                    SELECT *
                    FROM
                        (SELECT DS.documentName as documentName, MD.mainDocumentId as documentId, Lbl.label as label
                        FROM MainDocument as MD, Account as A, DocumentSetup as DS, Log as L, Document_Label as DL, Label as Lbl
                        WHERE MD.originId = A.userId 
                            AND MD.documentSetupId = DS.documentSetupId 
                            AND A.userId != '$userId'
                            AND MD.mainDocumentId = L.documentId
                            AND L.userId = '$userId'
                            AND MD.mainDocumentId = DL.documentId 
                            AND DL.mainLabel = '1' 
                            AND DL.labelId = Lbl.labelId
                        GROUP BY MD.mainDocumentId) as ConnectedDocs
                    WHERE documentId NOT IN
                        (SELECT documentId
                        FROM Log
                        WHERE activity = 'Archived')
                ";

            $docResults = mysql_query($queryDocs) or die ('Error in query: $queryDocs. ' . mysql_error());

            if ( mysql_num_rows($docResults) > 0 ) {
                // Start table
                echo "<span class='screenlet'>Received Documents</span>";
                echo "<table border='1' id='passByDocsTable' class='trckTableMainPage'>";
                
                // DISPLAY HEADERS
                echo "<tr>";
                echo "<td class='logHeader docIdTrck'>Document Id</td>";
                echo "<td class='logHeader docNameTrck'>Label</td>";
                echo "<td class='logHeader'>Track Document</td>";
                echo "</tr>";

                while( $docRow = mysql_fetch_array($docResults) ) {
                    echo "<tr>";
                    echo "<td><a href='javascript:;' class='hLinkViewPage' id='docId__".$docRow['documentId']."'>".$docRow['documentId']."</a></td>";
                    echo "<td>".$docRow['label']."</td>";
                    
                    // DISPLAY TRACK DOCUMENT
                    $documentId = $docRow['documentId'];

                    // Set the flag for track document that it will be to aligned to the left
                    $pageCalled = "mainPgTrckDoc";
                    include('trackDocument.php');

                    // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
                    if ( $prevStepCount < $totalStepCount )
                        $prevStepCount = $totalStepCount;

                    echo "</tr>";
                }
                
                mysql_free_result($docResults); // Free result
                echo "</table>"; // close table
            }
//            else {
//                // IF RETURNED QUERY IS EMPTY, THEN MESSAGE THE USER THAT THE RETURNED QUERY IS EMPTY
//                echo "<tr><td><span class='errorMessage'>No documents available.</span></td></tr>";
//            }
            ?>
        
        <!-- HIDDEN VARIABLES USED FOR ADJUSTMENT OF TABLE'S WIDTH -->
        <input id="passByStepCount" name="passByStepCount" type="hidden" value="<?php echo "$prevStepCount"; ?>" />
        <!-- END - DISPLAY DOCUMENTS THAT WHERE PASSED BY THE USER -->
        
        <!-- START - DISPLAY ACTIVE DOCUMENTS FOR USERS -->
        <?php
        // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
        $prevStepCount = 0;

        // GET THE DOCUMENTS
        $queryDocs =
            "
                SELECT *
                FROM
                    (
                    SELECT mainDocumentId as documentId, label
                    FROM MainDocument, Account_Dept_Pos, Department_Position, Document_Label DL, Label L
                    WHERE MainDocument.status = 'Active'
                        AND Account_Dept_Pos.userId = MainDocument.originId
                        AND L.labelId = DL.labelId
                        AND mainLabel = '1'
                        AND maindocumentId=documentId
                        AND Account_Dept_Pos.deptPosId = Department_Position.deptPosId
                        AND Department_Position.departmentId
                            IN (
                            SELECT departmentId
                            FROM Account_Dept_Pos ADP, Department_Position DP
                            WHERE ADP.status = 'Active'
                            AND ADP.userId = '$userId'
                            AND ADP.deptPosId = DP.deptPosId
                            )
                    GROUP BY mainDocumentId
                    ) as Docs
                WHERE documentId NOT IN 
                    (
                        SELECT documentId
                        FROM Log
                        WHERE userId = '$userId'
                        GROUP BY documentId
                    )
            ";

        $docResults = mysql_query($queryDocs) or die ('Error in query: $queryDocs. ' . mysql_error());

        if ( mysql_num_rows($docResults) > 0 ) {
            // Start table
            echo "<span class='screenlet'>Active Documents</span>";
            echo "<table border='1' id='allActvUsrDocsTable' class='trckTableMainPage'>";
            
            // DISPLAY HEADERS
            echo "<tr>";
            echo "<td class='logHeader docIdTrck'>Document Id</td>";
            echo "<td class='logHeader docNameTrck'>Label</td>";
            echo "<td class='logHeader'>Track Document</td>";
            echo "</tr>";

            while( $docRow = mysql_fetch_array($docResults) ) {
                echo "<tr>";
                echo "<td><a href='javascript:;' class='hLinkViewPage' id='docId__".$docRow['documentId']."'>".$docRow['documentId']."</a></td>";
                echo "<td>".$docRow['label']."</td>";
                
                // DISPLAY TRACK DOCUMENT
                $documentId = $docRow['documentId'];

                // Set the flag for track document that it will be to aligned to the left
                $pageCalled = "mainPgTrckDoc";
                include('trackDocument.php');

                // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
                if ( $prevStepCount < $totalStepCount )
                    $prevStepCount = $totalStepCount;

                echo "</tr>";
            }

            mysql_free_result($docResults); // Free result
            echo "</table>"; // close table
        }
//        else {
//            // IF RETURNED QUERY IS EMPTY, THEN MESSAGE THE USER THAT THE RETURNED QUERY IS EMPTY
//            echo "<tr><td><span class='errorMessage'>No documents available.</span></td></tr>";
//        }
        ?>
        
        <!-- HIDDEN VARIABLES USED FOR ADJUSTMENT OF TABLE'S WIDTH -->
        <input id="allActvUsrStepCount" name="allActvUsrStepCount" type="hidden" value="<?php echo "$prevStepCount"; ?>" />
        <!-- END - DISPLAY ACTIVE DOCUMENTS FOR USERS -->
        
    <?php
    }
    else {
    ?>
        <!-- START - DISPLAY ACTIVE DOCUMENTS FOR ADMIN -->
        <?php
        // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
        $prevStepCount = 0;

        // GET THE DOCUMENTS
        $queryDocs =
            "
                SELECT *
                FROM
                    (SELECT DS.documentName as documentName, MD.mainDocumentId as documentId, Lbl.label as label
                    FROM MainDocument as MD, DocumentSetup as DS, Log as L, Document_Label as DL, Label as Lbl
                    WHERE MD.documentSetupId = DS.documentSetupId
                        AND MD.mainDocumentId = L.documentId
                        AND MD.mainDocumentId = DL.documentId 
                        AND DL.mainLabel = '1' 
                        AND DL.labelId = Lbl.labelId
                    GROUP BY MD.mainDocumentId) as ConnectedDocs
                WHERE documentId NOT IN
                    (SELECT documentId
                    FROM Log
                    WHERE activity = 'Archived')
            ";

        $docResults = mysql_query($queryDocs) or die ('Error in query: $queryDocs. ' . mysql_error());

        if ( mysql_num_rows($docResults) > 0 ) {
            // Start table
            echo "<span class='screenlet'>Active Documents</span>";
            echo "<table border='1' id='allActvAdmDocsTable' class='trckTableMainPage'>";
            
            // DISPLAY HEADERS
            echo "<tr>";
            echo "<td class='logHeader docIdTrck'>Document Id</td>";
            echo "<td class='logHeader docNameTrck'>Label</td>";
            echo "<td class='logHeader'>Track Document</td>";
            echo "</tr>";

            while( $docRow = mysql_fetch_array($docResults) ) {
                echo "<tr>";
                echo "<td><a href='javascript:;' class='hLinkViewPage' id='docId__".$docRow['documentId']."'>".$docRow['documentId']."</a></td>";
                echo "<td>".$docRow['label']."</td>";
                
                // DISPLAY TRACK DOCUMENT
                $documentId = $docRow['documentId'];

                // Set the flag for track document that it will be to aligned to the left
                $pageCalled = "mainPgTrckDoc";
                include('trackDocument.php');

                // $prevStepCount will be used for the adjustment of table's width when it reached 13 circles
                if ( $prevStepCount < $totalStepCount )
                    $prevStepCount = $totalStepCount;

                echo "</tr>";
            }

            mysql_free_result($docResults); // Free result
            echo "</table>"; // close table
        }
//        else {
//            // IF RETURNED QUERY IS EMPTY, THEN MESSAGE THE USER THAT THE RETURNED QUERY IS EMPTY
//            echo "<tr><td><span class='errorMessage'>No documents available.</span></td></tr>";
//        }
        ?>    
        
        <!-- HIDDEN VARIABLES USED FOR ADJUSTMENT OF TABLE'S WIDTH -->
        <input id="allActvAdmStepCount" name="allActvAdmStepCount" type="hidden" value="<?php echo "$prevStepCount"; ?>" />
        <!-- END - DISPLAY ACTIVE DOCUMENTS FOR ADMIN -->
    <?php
    }
    ?>
    
    <!-- INVISIBLE FORM WHICH WILL BE USED FOR TRANSFERRING THE DOCUMENT TO ITS VIEW PAGE -->
    <form id="viewPageForm" name="viewPageForm" action="viewPageSending.php" method="post">
        <input id="passedId" name="documentId" type="hidden" value="" />
    </form>
    
    <?php
    }
    else {
        echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
    }
    // End checking permission
    ?>
</div>
    
<?php     
    include ("siteBottom.php"); 
?>
